﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Com.Seezt.Skins;
using Components;
using UI.Lib;
using UI.ParentForm;
using UI.Lib.Factory;
using System.Collections;

namespace UI.Sysset
{
    public partial class FrmImportProduct : BaseMedit
    {
        private DataTable dtSource = null; //当前
        protected bool? IsValidation = null;

        public FrmImportProduct(string modulecode, string action)
            : base(modulecode, action)
        {
            InitializeComponent();

            //回写的方法
            this.SaveCallFuntion = "ImportManager$ImportData"; //保存的方法
            IsAfterSaveCloseWin = false;
            this.tspSave.Text = "导入";

            this.tspBtnAdd.Visible = this.tspBtnDel.Visible = false;
            this.tspDtlTop.Items.Add(base.CreateToolBtn("W", "预览数据(&K)",
                delegate
                {
                    string errmsg = this.tbSummary.CheckSelf();
                    if (!string.IsNullOrEmpty(errmsg))
                    {
                        MsgBox.ShowErrorMsg(this, errmsg);
                        return;
                    }

                    LoadExcelData();
                }));


            //加入验证数据合法性的按钮
            this.tspDtlTop.Items.Add(base.CreateToolBtn("C", "验证数据合法性(&C)",
                delegate
                {
                    if (
                        MsgBox.Show(this, "提示", "验证数据合法性可能需要等待一段时间，是否继续？",
                                    MessageBoxButtons.YesNo) ==
                        System.Windows.Forms.DialogResult.No)
                    {
                        return;
                    }

                    DoCheck();

                    if (true == this.IsValidation)
                    {
                        MsgBox.Show(this, "数据检测OK, 可以进行导入！");
                        this.dgvDtl.ReadOnly = true;
                    }
                }));
        }

        /// <summary>
        /// 加载Excel的数据
        /// </summary>
        void LoadExcelData()
        {
            if (this.dgvDtl.Rows.Count > 0 && MsgBox.Show(this, "提示", "重新预览会清除上一次预览的明细记录，\n是否继续？", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }

            this.dgvDtl.ReadOnly = false;
            this.dgvDtl.DataSource = null; //先清空明细列表

            string filePath = Validation.ToString(tbSummary.GetValue("exlpath"));
            DataSet ds = new DataSet();

            ExportHelper help = new ExportHelper(filePath, ref ds);
            if (!help.Convert(1)) //读取的一个sheet中的内容
            {
                MsgBox.ShowErrorMsg(this, "您选择的文件异常，无法导入！");
                return;
            }

            if (ds.Tables.Count == 0)
            {
                MsgBox.ShowErrorMsg(this, "您选择的不是一个有效的文件，无法导入！");
                return;
            }

            dtSource = ds.Tables[0];
            this.dgvDtl.DataSource = dtSource;

            MsgBox.Show(this, string.Format("数据加载成功，共计 {0} 条数据！", dtSource.Rows.Count));
        }

        protected override bool Check()
        {
            if (0 == this.dgvDtl.Rows.Count)
            {
                MsgBox.Show(this, "明细中没有数据，不能做导入！");
                return false;
            }

            if (null == this.IsValidation) //未做过验证
            {
                DoCheck();
            }

            if (false == this.IsValidation)
            {
                MsgBox.ShowErrorMsg(this, "导入的数据不符合规范，请教正后重新做导入！");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 验证数据合法性
        /// </summary>
        void DoCheck()
        {
            this.dgvDtl.EndEdit();

            if (null == dtSource || dtSource.Rows.Count == 0)
            {
                MsgBox.ShowErrorMsg(this, "没有数据可供检测！");
                return;
            }

            string[] cols = new string[] { "code", "family", "po", "kind", "brand", "dw", "dj",
                                "tax", "cbfs" };
            DataTable dtCheck = DataTableHelper.Entity.MarkColumn(null, cols);
            DataRow dr = dtCheck.NewRow();
            foreach (string s in cols)
            {
                dr[s] = DistinctString(s);
            }

            dtCheck.Rows.Add(dr);

            Hashtable tb = new Hashtable();
            tb["comcode"] = this.tbSummary.GetValue("comcode");
            //调用服务器方法保存数据
            string result = CommonHelper.Entity.SaveDtl("ImportManager$CheckProducts",
                StringUtil.Entity.TableToJson(tb), "C", dtCheck, null);

            tb = null;

            if (!string.IsNullOrEmpty(result)) //验证不通过
            {
                MsgBox.Show(this, result);
                IsValidation = false;
                return;
            }

            IsValidation = true;
        }

        public override bool BeforePopWin(string name, ref string where, ref string[] others)
        {
            if ("rolecode" == name)
            {
                if (!Context.IsSuperUser)
                {
                    where = string.Format(" (comcode = '{0}' OR comcode IS NULL) ", Context.User.Comcode);
                }
            }
            return true;
        }


        string DistinctString(string groupby)
        {
            DataView dview = dtSource.DefaultView;
            //取出数据源中的具体行
            DataTable dtRowFilter = dview.ToTable(false, groupby);

            dview = null;
            if (dtRowFilter == null || 0 == dtRowFilter.Rows.Count) return "";
            //对行进行Distinct
            dview = dtRowFilter.DefaultView;
            DataTable distinctTable = dview.ToTable(true, groupby);

            if (distinctTable == null || 0 == distinctTable.Rows.Count) return "";

            /*
            if ("code" == groupby && distinctTable.Rows.Count != dtSource.Rows.Count)
            {
                MsgBox.Show(this, "当前Excel中商品编码存在重复，请检查！");
                return "";
            }
            */

            StringBuilder sb = new StringBuilder();
            foreach (DataRow dr in distinctTable.Rows)
            {
                if (sb.Length != 0) sb.Append(",");

                sb.Append(Validation.ToString(dr[0]).Replace("'", "''").Replace(",", "").Trim());
            }

            return sb.ToString();
        }
    }
}
